package com.springboot.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import com.springboot.enums.CodeEnum;
import com.springboot.mapper.UsersinfoMapper;
import com.springboot.pojo.Usersinfo;
import com.springboot.utils.RedisUtil;
import com.springboot.utils.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UsersinfoService  {

    @Resource
    UsersinfoMapper usersinfoMapper;

    /**
     * Redis 工具类
     */
    @Resource
    private RedisUtil redisUtil;

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public ResultUtil login(String username, String password) {
        if(StrUtil.hasEmpty(username)){
            return ResultUtil.Error("用户名不能为空");
        }

        if(StrUtil.hasEmpty(password)){
            return ResultUtil.Error("密码不能为空");
        }

        Usersinfo usersinfo = usersinfoMapper.login(username);

        if (usersinfo==null){
            return ResultUtil.Error("用户名不存在");
        }

        String userPwd = SecureUtil.md5(password+usersinfo.getPwdsalt());
        if(userPwd.equals(usersinfo.getUserpwd())){
            JSONObject resJSONObject = new JSONObject();
            String Token = SecureUtil.md5(usersinfo.getId());
            redisUtil.set(Token,usersinfo,600);
            resJSONObject.set("token",Token);
            return ResultUtil.Success("登录成功",resJSONObject);
        }else{
            return ResultUtil.Error("密码错误");
        }
    }

    public ResultUtil getInfo(String token) {
        if(StrUtil.hasEmpty(token)){
            return  ResultUtil.Code(CodeEnum.INVALID_PARAMS.getCode(),"令牌不能为空","");
        }
        Usersinfo user = (Usersinfo) redisUtil.get(token);
        JSONObject resJSONObject = new JSONObject();
        resJSONObject.set("userName",user.getUsername());
        List<String> strings= new ArrayList<>();
        strings.add("test1");
        resJSONObject.set("roles",strings);
        resJSONObject.set("introduction","I am a super administrator");
        resJSONObject.set("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        if(user==null){
            return ResultUtil.Error("令牌不存在");
        }else{
            return ResultUtil.Success("获取成功",resJSONObject);
        }
    }


    public ResultUtil logout(String token) {
        redisUtil.del(token);
        return ResultUtil.Success("退出成功");
    }

    /**
     * 密码加密
     */
    public static void main(String[] args) {
        System.out.println(SecureUtil.md5("admin"+123));
    }


}
